package web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import service.ImpUserServiceByServlet;
import service.UserService;
import util.ImageUtil;
import util.Result;
import util.ServletUtil;

public class MainServlet extends HttpServlet{

	/**
     * 
     */
    private static final long serialVersionUID = 1L;

    /* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String path = req.getServletPath();
		if("/earnImg.do".equals(path)){
			//System.out.println("欢迎来到earnImg.do");
			createImg(req, res);
		} else if("/log_in.do".equals(path)){
			//System.out.println("欢迎登陆");
			log_in(req,res);
		} else {
			//错误的路径
			throw new RuntimeException("没有这个页面");
		}
		
	}
	
	/**
	 * @param req
	 * @param res
	 * @throws ServletException
	 * @throws IOException
	 * 登录验证
	 */
	private void log_in(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		UserService service = null;
		//定义结果对象
		Result result = null;
		//定义返回json数据包
		JSONObject result_json = null;
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=UTF-8");
		HttpSession session = req.getSession();
		String code = (session.getAttribute("imgCode")).toString();
		//json请求数据包
		JSONObject json_pack = null;
		try {
			json_pack = ServletUtil.red_req_json(req,res);
			//System.out.println(json_pack.getString("user_id"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json异常");
			e.printStackTrace();
		}
		//验证 验证码 的正确性 取session里面的值跟请求值比较
		try {
			if(!json_pack.getString("key_code").toLowerCase().equals(code.toLowerCase())){
				//System.out.println("验证码错误");
				//设置返回数据 对象
				//第三个参数为Object对象，这里传入的对象，new JSONObject(result)都能逐层解析成对应Json
				result = new Result("0000","验证码错误","");
			}else {
				//System.out.println("验证码正确");
				//验证用户名跟密码
				service = new ImpUserServiceByServlet();
				result = service.login_check_user(json_pack.getString("user_id"), json_pack.getString("user_pwd"));
			}
			if(!"0001".equals(result.getCode())){
				//用于更新验证码图片
				result.setData(ServletUtil.update_img(req));
			}
			//设置json内容
			result_json = new JSONObject(result);//!!!!!!!!!!!!!!!!!!!!!!!牛 逼
			//写出json对应字符串
			ServletUtil.res_send_json(req, res,result_json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("JSONObject Exception");
			e.printStackTrace();
		}
		
		System.out.println("log_in over");
	}

	protected void createImg(
			HttpServletRequest req, 
			HttpServletResponse res) 
			throws ServletException, IOException {
			//生成随机的验证码和图片                                                                                  
			Object[] objs = ImageUtil.createImage();
			//将验证码存入session
			HttpSession session = req.getSession();
			session.setAttribute("imgCode", objs[0]);
			//将图片输出给浏览器
			BufferedImage img = 
				(BufferedImage) objs[1];
			//格式见/tomcat/conf/web.xml
			res.setContentType("image/png");
			//该输出流的目标就是浏览器
			OutputStream os = null;
			os = res.getOutputStream();
			//ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(img, "png", os);
			/*byte[] bytes = bos.toByteArray();
			String s = new String(Base64.encode(bytes));
			System.out.println(s);
			PrintWriter out = null;
			out = res.getWriter();
			out.print(s);
			out.flush();
			if (out != null){
				out.close();
				System.out.println("over");
			}*/
			if(os != null){
				os.close();
				//System.out.println("servlet Over!!!!!!!");
			}
		}
	
}
